import JSZip from 'jszip';

export const extractZipFile = (zipFilePath) => {
  return new Promise((resolve, reject) => {
    // 使用 plus.io 读取文件
    plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENT, (fs) => {
      fs.readFile(zipFilePath, 'binary', (data) => {
        const zip = new JSZip();
        zip.loadAsync(data)
          .then((zipContent) => {
            let systemFiles = {};
            zipContent.forEach((relativePath, file) => {
              systemFiles[relativePath] = file;
            });
            resolve(systemFiles);
          })
          .catch((err) => {
            reject('解压失败: ' + err.message);
          });
      }, (err) => {
        reject('文件读取失败: ' + err.message);
      });
    });
  });
};

export const readSystemFiles = () => {
  return new Promise((resolve, reject) => {
    const systems = [];
    const systemFolder = '/storage/emulated/0/systems';  // Android 中的文件路径
    plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENT, (fs) => {
      fs.readDir(systemFolder, (files) => {
        // 过滤出 ZIP 文件
        files.forEach((file) => {
          if (file.isFile && file.name.endsWith('.zip')) {
            systems.push({ name: file.name, path: systemFolder + '/' + file.name });
          }
        });
        resolve(systems);
      }, (err) => {
        reject(err);
      });
    });
  });
};
